package csm.web.core.search.IR;

import java.io.IOException;
import java.util.List;

import org.jdom.Element;
import org.jdom.JDOMException;

import csm.common.StringUtil;
import csm.common.xml.XmlDocument;
import csm.web.core.search.BriefItem;
import csm.web.core.search.SearchResultInfo;

public class IRSearchResult extends SearchResultInfo {

	@SuppressWarnings("unchecked")
	@Override
	public void parseResult(String responseString) {

		int hitcount = 0;
		int pageSize = 10;
		int page = 1;
		int startRow=0;

		if(StringUtil.isNullOrEmpty(responseString)) return;

		//System.out.println(responseString);

		setResultString(responseString);

		XmlDocument xmlDoc = null;
		try {
			responseString.replaceAll("&\\#x[0-9][A-F]?;", " ");
			xmlDoc = new XmlDocument(responseString);

			List<Element> lstNodes = xmlDoc.selectNodes("/response/lst/lst/str");
			for(Element lstNode : lstNodes){
				if( lstNode.getAttributeValue("name").equalsIgnoreCase("rows")){
					pageSize = Integer.parseInt(lstNode.getText());
				}
				else if( lstNode.getAttributeValue("name").equalsIgnoreCase("start")){
					startRow  = Integer.parseInt(lstNode.getText());
				}
				else if( lstNode.getAttributeValue("name").equalsIgnoreCase("q")){
					 //setQuery( lstNode.getText() );
				}
			}

			if( pageSize <= 0)
				pageSize = 10;

			page = (startRow / pageSize) + 1;
			Element resultNode = (Element)xmlDoc.selectSingleNode("/response/result");

			hitcount = Integer.parseInt( resultNode.getAttributeValue("numFound") );
			setHitCount(hitcount);

			setPageSize(pageSize);
			setPage(page);

			if( hitcount <=0) return;

			String fieldName;
			String fieldVal;

			BriefItem item;
			List<Element> docNodes = resultNode.getChildren();
			for( Element doc : docNodes )
			{
				item = new BriefItem();
				List<Element> nodes = doc.getChildren();
				for( Element node : nodes )
				{
					if (node.getName().equalsIgnoreCase("str"))
					{
						fieldName = node.getAttributeValue("name");
						fieldVal = node.getText();
						item.add(fieldName, fieldVal);

						//System.out.println(fieldName + ":" + fieldVal);
					}
					else
					{
						fieldName = node.getAttributeValue("name");
						List<Element> subNodes = node.getChildren();
						for (Element subNode : subNodes)
						{
							fieldVal = subNode.getText();
							item.add(fieldName, fieldVal);
							//System.out.println(fieldName + ":" + fieldVal);
						}
					}
				}
				this.addBriefItem(item);
			}

		} catch (JDOMException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}
